package com.uni.action;


import com.uni.entity.Commodity;
import com.uni.entity.User;

import com.uni.service.Service;
import com.uni.utils.FileUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * --------------project-------------
 *
 * @Author Unirithe  - Mr.Chao
 * - CSDN:
 * https://blog.csdn.net/Unirithe
 * - GitHub:
 * https://github.com/unirithe
 * @create 2021/12/21 20:35
 * ------------------------------------------
 */
@WebServlet(name = "CommodityPublishAction", urlPatterns = "/publish")
public class CommodityPublishAction extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        req.setCharacterEncoding("utf-8");
        // 【获取用户以及用户填写的商品信息】
        User user = (User) req.getSession().getAttribute("userInfo");
//        // 【新建商品对象】
        Commodity commodity = new Commodity();
        commodity.setUid(user.getId());
        commodity.setName(FileUtil.read(req, "commodity-name"));
        commodity.setInfo(FileUtil.read(req, "commodity-info"));
        commodity.setTid(Integer.parseInt(FileUtil.read(req, "commodityType")));
        commodity.setPrice(Float.parseFloat(FileUtil.read(req, "commodity-price")));
//        System.out.println("读取表单信息后" + commodity);
        // 【获取商品名称】
        String path0 = req.getServletContext().getRealPath( "./") + File.separator + user.getName() + File.separator;
        String path1 = commodity.getName() + ".jpg";
        if(FileUtil.saveFile(req, path0, path1)==true) {
            commodity.setImg(user.getName() + File.separator + path1);
            Service.commodity.insertCommodity(commodity);
            resp.getWriter().write("操作成功");
        } else{
            resp.getWriter().write("操作失败");
        }


    }
}
